import React from 'react';
import { connect } from 'dva/index';
import { Button, Checkbox, Col, DatePicker, Form, Input, message, Radio, Row, Table } from 'antd';
import Constants from '../../utils/Constants';
import RightConstants from '../../utils/RightConstants';
import OrderChargeInfo from '../../components/logisticsOrder/orderChargeInfo';
import PaymentDetail from '../../components/finance/paymentDetail';
import RightBox from '../../components/common/rightBox';
import { download } from '../../utils/commons';

const RadioGroup = Radio.Group;
const CheckboxGroup = Checkbox.Group;
const dateFormat = 'YYYY-MM-DD';
const { RangePicker } = DatePicker;
const typeArr = ['应付', '应收'];
const status = ['删除', '草稿', '业务已确认', '变更申请中', '变更已审核', '变更新增', '业务确认中'];
const FormItem = Form.Item;
const R = require("ramda");

const batchVerificate = Form.create()(class BatchVerificate extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            chargeKeys: [],
            charges: []
        }
    }

    componentDidMount() {
        this.props.dispatch({ type: 'orderCharge/queryChargesForPage', payload: { ...R.pick(['page', 'size'], Constants.DEFAULT_PAGE) } });
    }

    handleOpen = (id) => {
        if (id) {
            this.props.dispatch({
                type: 'orderCharge/getOdChargeById',
                payload: { id }
            })
        }
        this.props.dispatch({ type: 'feeItem/getAllFeeItems' });
        this.orderChargeInfo.handleOpen(id, null, false, false, true);
    }

    handleApply = () => {
        if (!this.state.charges || this.state.charges.length === 0) {
            message.error("请先选择要冲账的费用"); return;
        }
        const errorMsgs = ['结算单位不一致，请重新选择', '币种不一致，请重新选择', '应收合计不能超过应付合计，请重新选择'];
        let [currency, receiver, flag, payment, revenue, paymentList, revenueList, currentOrderNo] = [undefined, undefined, undefined, 0, 0, [], [], undefined];
        this.state.charges.map((item) => {
            if(!flag){
                currentOrderNo = item.orderNo;
                receiver = receiver ? receiver : item.settlementUnit;
                currency = currency ? currency : item.currency;
                flag = receiver != item.settlementUnit ? 1 : flag;
                flag = currency != item.currency ? 2 : flag;
                payment = payment + (item.type === '0' ? item.verificateAmout : 0); //应付合计
                revenue = revenue + (item.type === '1' ? item.verificateAmout : 0); //应收合计
                if (item.type === '0') paymentList.push(item);
                else revenueList.push(item);
            }
        })
        /*         flag = flag ? flag : (revenue > payment ? 3 : undefined); */
        if (flag) { message.error(currentOrderNo + errorMsgs[flag - 1]); return }

        //为了重置modal的dataSource, 别删
        this.props.dispatch({
            type: 'payment/getPaymentById',
            payload: { id: undefined }
        });
        this.paymentDetail.handleOpen({ disabled: false, receiver, batchFlag: true, paymentList, revenueList });
    }

    handleExport = () => {
        if (!this.state.charges || this.state.charges.length === 0) {
            message.error("请先选择要导出的费用"); return;
        }
        let settlementUnit = undefined;
        let flag = false;
        let currentOrderNo = "";
        this.state.charges.map((item) => {
            if(!flag){
                if(!settlementUnit){
                    settlementUnit = item.settlementUnit;
                }else{
                    if(settlementUnit !== item.settlementUnit){
                        currentOrderNo = item.orderNo;
                        flag = true;
                    }
                }
            }
        })
        if (flag) { message.error(currentOrderNo + "结算单位不一致，请重新选择"); return };

        let values = this.props.form.getFieldsValue();
        let beginDate = values.orderDate && values.orderDate.length > 0 ? values.orderDate[0].format(Constants.DATEFORMAT) : undefined;
        let endDate = values.orderDate && values.orderDate.length > 1 ? values.orderDate[1].format(Constants.DATEFORMAT) : undefined;
        let feeIds = this.state.chargeKeys;
        let url = apiPath.mc + "/api/odCharge/generate";
        download(url, {beginDate, endDate, feeIds});
    }

    cleanSelected = () => {
        this.setState({ chargeKeys: [], charges: [] });
    }

    handleSearch = (flag) => {
        let values = this.props.form.getFieldsValue();
        let newPage = R.pick(['page', 'size'], this.props.orderCharge.page);
        values.beginDate = values.orderDate && values.orderDate.length > 0 ? values.orderDate[0].format(Constants.DATEFORMAT) : undefined;
        values.endDate = values.orderDate && values.orderDate.length > 1 ? values.orderDate[1].format(Constants.DATEFORMAT) : undefined;
        values.orderDate = undefined;
        if (flag) {
            newPage.page = 1;
        }

        this.props.dispatch({
            type: 'orderCharge/queryChargesForPage',
            payload: {
                ...values,
                ...newPage
            }
        });
    };

    columns = [
        { title: '接单时间', dataIndex: 'creattime', key: 'creattime' },
        { title: '结算单位', dataIndex: 'settlementUnit', key: 'settlementUnit' },
        { title: '订单编号', dataIndex: 'orderNo', key: 'orderNo' },
        { title: 'SO号', dataIndex: 'soNo', key: 'soNo' },
        { title: '柜号', dataIndex: 'cntrNo', key: 'cntrNo' },
        { title: '名称', dataIndex: 'feeItemName', key: 'feeItemName' },
        { title: '币种', dataIndex: 'currency', key: 'currency' },
        { title: '金额', dataIndex: 'quotePrice', key: 'quotePrice' },
        { title: '余额', dataIndex: 'verificateAmout', key: 'verificateAmout' },
        { title: '类型', key: 'type', render: (text, record, index) => { return <span>{typeArr[record.type]}</span> } },
        { title: '状态', key: 'status', render: (text, record, index) => { return <span>{status[record.status]}</span> } },
        {
            title: '操作', key: 'key_oprator',
            render: (text, record, index) => {
                let viewLink = <a href="#" onClick={this.handleOpen.bind(this, record.id, null, false, false, true)}>查看</a>
                return <span>{viewLink}</span>;
            }
        }
    ];

    render() {
        let formItemLayout = { labelCol: { span: 8 }, wrapperCol: { span: 16 } };
        const { getFieldDecorator } = this.props.form;
        let pagination = {
            showTotal: total => `共 ${total} 条数据`,
            pageSize: this.props.orderCharge.page.size,
            current: this.props.orderCharge.page.page,
            total: this.props.orderCharge.page.totalRow,
            showSizeChanger: true,
            onShowSizeChange: (current, size) => {
                let newPage = R.pick(['page', 'size'], this.props.orderCharge.page);
                newPage.size = size;
                newPage.page = 1;
                let values = this.props.form.getFieldsValue();
                values.beginDate = values.orderDate && values.orderDate.length > 0 ? values.orderDate[0].format(Constants.DATEFORMAT) : undefined;
                values.endDate = values.orderDate && values.orderDate.length > 1 ? values.orderDate[1].format(Constants.DATEFORMAT) : undefined;
                values.orderDate = undefined;
                this.props.dispatch({
                    type: 'orderCharge/queryChargesForPage',
                    payload: {
                        ...values,
                        ...newPage
                    }
                });
            },
            onChange: (pageNumber, pageSize) => {
                let newPage = R.pick(['page', 'size'], this.props.orderCharge.page);
                newPage.page = pageNumber;
                let values = this.props.form.getFieldsValue();
                values.beginDate = values.orderDate && values.orderDate.length > 0 ? values.orderDate[0].format(Constants.DATEFORMAT) : undefined;
                values.endDate = values.orderDate && values.orderDate.length > 1 ? values.orderDate[1].format(Constants.DATEFORMAT) : undefined;
                values.orderDate = undefined;
                this.props.dispatch({
                    type: 'orderCharge/queryChargesForPage',
                    payload: {
                        ...values,
                        ...newPage
                    }
                });
            }
        }

        let rowSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    chargeKeys: selectedRowKeys
                })
            },
            onSelect: (record, selected, selectedRows, nativeEvent) => {
                let charges = [...this.state.charges];
                if (selected) charges.push(record)
                else charges = R.difference(charges, [record]);
                this.setState({ charges });
            },
            onSelectAll: (selected, selectedRows, changeRows) => {
                let charges = [...this.state.charges];
                if (selected) charges = charges.concat(changeRows);
                else charges = R.difference(charges, changeRows);
                this.setState({ charges });
            },
            selectedRowKeys: this.state.chargeKeys
        };

        return (
            <div>
                <Row>
                    <Col span={8}><FormItem {...formItemLayout} label={'结算单位'}>{getFieldDecorator('settlementUnit')(<Input />)}</FormItem></Col>
                    <Col span={8}>
                        <FormItem {...formItemLayout} label={'接单时间'}>
                            {getFieldDecorator('orderDate')(
                                <RangePicker
                                    style={{ width: '100%' }}
                                    showTime={{ format: 'YYYY-MM-DD' }}
                                    format="YYYY-MM-DD"
                                    placeholder={['开始时间', '结束时间']}
                                />
                            )}
                        </FormItem>
                    </Col>

                </Row>
                <Row>
                    <Col span={8}><FormItem {...formItemLayout} label={'核心编号'}>{getFieldDecorator('coreNo')(<Input placeholder="订单编号/so号/柜号"/>)}</FormItem></Col>
                    <Col span={8} style={{ float: 'left', marginLeft: 80 }}>
                        <Button type="primary" icon="search" style={{ marginLeft: 5 }}
                            onClick={this.handleSearch.bind(this, true)}>查询</Button>
                        <Button type="primary" icon="export" style={{ marginLeft: 5 }} onClick={this.handleExport.bind(this)} size={'default'}>导出对账单</Button>
                        <RightBox resource={RightConstants.ORDER.ORDER_FINANCE_VERIFICATE_APPLY}>
                            <Button type="primary" icon="plus" style={{ marginLeft: 5 }} onClick={this.handleApply.bind(this)} size={'default'}>冲账申请</Button></RightBox>
                    </Col>
                </Row>
                <Table
                    title={() => <span>已选择
                        <a style={{ fontWeight: 600, marginLeft: 5 }}>{this.state.chargeKeys.length}</a> 项
                        <a onClick={this.cleanSelected.bind(this)} style={{ marginLeft: 10 }}>清空</a></span>}
                    loading={this.props.loading}
                    rowKey='id'
                    dataSource={this.props.orderCharge.list}
                    columns={this.columns}
                    bordered={true}
                    size={'middle'}
                    pagination={pagination}
                    rowSelection={rowSelection} />
                <OrderChargeInfo wrappedComponentRef={(inst) => this.orderChargeInfo = inst} />
                <PaymentDetail wrappedComponentRef={(inst) => this.paymentDetail = inst} refreshList={this.handleSearch} />
            </div>
        );
    }
})

function mapStateToProps(state) {
    return {
        loading: state.loading.models.orderCharge, orderCharge: state.orderCharge
    };
}

export default connect(mapStateToProps)(batchVerificate);
